using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Forecast.Database;

public partial class Prediction : System.Web.UI.Page
{
    Forecast.Database.Prediction _prediction;
    Forecast.Database.Load _load;

    protected void Page_Load(object sender, EventArgs e)
    {
        _offerEditor.OfferCreated += new OfferCreatedEventHandler(_offerEditor_OfferCreated);
                
        if (string.IsNullOrEmpty(Request["id"])) throw new Exception("Missing argument - don't know which prediction to use.");

        _load = new Forecast.Database.Load(ConfigurationManager.ConnectionStrings["ForecastDB"].ConnectionString);
        _prediction = _load.GetPrediction(Int32.Parse(Request["id"]));
        
        Title = "The Forecast Exchange - New offer on " + _prediction.Ticker;
        _subHead.Text = string.Format("{0}: {1}<br/>",
                _prediction.IsActive ? "<b>End date</b>" : "<b>Ended</b>",
                _prediction.EndDate.ToLongDateString());
        _status.Text = "<b>Current value:</b> " + _prediction.LastValue;
        _status.Text += "<br />";
        _status.Text += "<b>Last change:</b> " + GetLastChange();
        _status.Text += "<br />";
        _status.Text += "<b>You currently have " + GetNumStocks() + " stocks you can put up for sale. </b>";

        ViewState["predictionId"] = _prediction.Id;
        RefreshData();
    }

    protected string GetLastChange()
    {
        return string.Format("<span style=\"color:{0};\">{1}{2}%</span>",
            (_prediction.LastChange >= 0 ? "green" : "red"),
            (_prediction.LastChange >= 0 ? "+" : ""),
            _prediction.LastChange);
    }

    protected string GetNumStocks()
    {
        Player player = _load.GetPlayer(UserHelper.GetUserId(Page.User.Identity.Name));
        Holding holding = _load.GetHolding(player, _prediction);

        if (holding == null)
            return "0";
        else
            return holding.NumPredictions.ToString();
    }

    protected string GetTicker()
    {
        return _prediction.Ticker;
    }

    protected string GetGoBackLink()
    {
        return string.Format("<a href=\"Prediction.aspx?id={0}\">Go back</a>", _prediction.Id);
    }
 
    void _offerEditor_OfferCreated(object sender, EventArgs e)
    {
        RefreshData();
    }

    private void RefreshData()
    {
        int predictionIdFromViewstate = Convert.ToInt32(ViewState["predictionId"].ToString());

        _offerEditor.Initialize(predictionIdFromViewstate);
    }
}
